package android.timer.com;

import java.text.Format;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.R.bool;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.text.format.Formatter;
import android.text.format.Time;
import android.text.method.DateTimeKeyListener;
import android.timer.com.R.drawable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DigitalClock;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;

public class android_timer extends Activity {
	/* 0 = Silent Mode | 1 = Vibrate Mode | -1 = Normal Mode */

	Boolean messageBox_Status = false;
	TextView REMAINING_TIME; //textview to display the countdown
	private static boolean IS_TIMER_ON;
	private int VOLUMN_MODE =0;  
	private int CURRENT_RINGERMODE;
	private MyCount counter= null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        REMAINING_TIME = (TextView) findViewById(R.id.lblTime);
        AudioManager   mAudio = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
        CURRENT_RINGERMODE = mAudio.getMode();
        
        //tv = new TextView(this);
        //this.setContentView(tv);
        //5000 is the starting number (in milliseconds)
        //1000 is the number to count down each time (in milliseconds)
        //MyCount counter = new MyCount(5000,1000);
        //counter.start();
        //AudioManager   mAudio = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
        //mAudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        setContentView(R.layout.main);
        
        Button defaultButton = (Button)findViewById(R.id.bttDefault);
        if(defaultButton != null)
        {
        	defaultButton.setOnClickListener(new View.OnClickListener() {

          @Override
          public void onClick(View view) {
        	  EditText defaultMints = (EditText) findViewById(R.id.timepicker_input);
        	  defaultMints.setText(R.string.default_time);
         }
        });
        }
    	  EditText Input_TimePicker = (EditText)findViewById(R.id.timepicker_input);
    	  Input_TimePicker.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				UpdateTime(s);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				
			}
		});
  	  
    	 
    	Button bttExit = (Button) findViewById(R.id.bttCancel);
    	bttExit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				if(IS_TIMER_ON){
					Counter(false, 1000);
					RestoreSettings(); // to Stop Time
				}
				else
					finish();
			}

		});
    	
    	Button bttActivate = (Button) findViewById(R.id.bttActivate);
    	bttActivate.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				EditText Input_TimePicker = (EditText)findViewById(R.id.timepicker_input);
				int minutes  = Integer.parseInt(Input_TimePicker.getText().toString());
				if(minutes != 0){
				int milliSec = minutes * 60 * 1000; /* Convert: minutes to secs x 10^-3 */ 
				Counter(true, milliSec);
			    Settings();
			    
			    ConfirmationMessageBox("Do you want to go back to Home?", "Timer is Start");
			   
				}
				else
				{
					Common common = new Common(android_timer.this);
					common.MessageBox("Counter must be greater than 0", "Error");
					
				}
			}
		   
		});
    	 Button btn=(Button)findViewById(R.id.bttSelectTime);
    	 	 
    	 	final OnTimeSetListener  timeListner =new OnTimeSetListener()
    	 	        {
    	 	 
    	 	   public void onTimeSet(TimePicker  arg0, int hourOfDay, int minute) {
    	 	    // TODO Auto-generated method stub
    	 		   	TextView txt =(TextView)findViewById(R.id.lblTime);
    	 		   	EditText txtInputTime =(EditText)findViewById(R.id.timepicker_input);
    	 		   	int minutesDifference = getMinuteDifference(hourOfDay,minute);
    	 		    txtInputTime.setText(String.valueOf(minutesDifference));
    	 		   	txt.setText(get12HoursFormat(hourOfDay, minute));
    	 			
    	 			
    	 	   }
    	 	        };
    	 	 
    	 	btn.setOnClickListener(new View.OnClickListener()
    	 	        {
    	 	 
    	 	   public void onClick(View arg0) {
    	 	    // TODO Auto-generated method stub
    	 	    
    	 	    Calendar cal=Calendar.getInstance();
    	 	   TimePickerDialog timePickDiag=new TimePickerDialog(android_timer.this,timeListner, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), false);
    	       timePickDiag.show();
    	 	   }
    	 	        }
    	 	         
    	 	        );
       updateDisplay();
    
    }
	private String get12HoursFormat(int hourOfDay, int mintute) {

		String period = "AM";
		int hrs = hourOfDay;
		hrs = hrs == 0 ? 12 : hrs;
		
		if(hourOfDay > 12)
			hrs = hourOfDay % 12;
		
		if(hourOfDay >= 12)
			period = "PM";
		
		//Format format  = new SimpleDateFormat("hh:mm a");
		NumberFormat myFormat = NumberFormat.getInstance();
		 myFormat.setMinimumIntegerDigits(2);
		return (String.valueOf(myFormat.format(hrs)) + ":" + String.valueOf(myFormat.format(mintute))+ " " + period);
	}
	private int getMinuteDifference(int hourOfDay, int minutes)
	{   
		int hrs = 0;
		 Date date = new Date();
		long current_hr = (long) date.getHours();
		hrs = hourOfDay == 0 ? 24 : hourOfDay;
		current_hr  = current_hr == 0 ? 24 : current_hr;
		
		long current_mint_of_the_day = (current_hr * 60) + date.getMinutes();
		long selected_mint_of_the_day = (hrs * 60) + minutes;
		long dMint = (selected_mint_of_the_day - current_mint_of_the_day);
		
		if(dMint < 0)
			dMint = 1440 + dMint;
		

		return (int) dMint;
	}
	public void UpdateTime(CharSequence s) {
		TextView txtTime = (TextView) findViewById(R.id.lblTime);
		
		//Calendar now = Calendar.getInstance();
		int duration = 0;
		duration = Integer.parseInt(s.toString());
		//now.add(Calendar.MINUTE, duration);
		
		Calendar c = Calendar.getInstance();// DateFormat.getTimeFormat(getApplicationContext()).getCalendar();
		//c.add(Calendar.HOUR, duration / 60);
		c.add(Calendar.MINUTE, duration);

			
		Format format  = new SimpleDateFormat("hh:mm a");
		String currentTime = format.format(c.getTime());
		String Time = String.valueOf(c.getTime());
		
		
		
		txtTime.setText(currentTime);
		
	}
	private void Settings() {
			
	    	Button bttActivate = (Button) findViewById(R.id.bttActivate);
	    	Button bttDefault = (Button) findViewById(R.id.bttDefault);
	    	Button bttSelectTime = (Button) findViewById(R.id.bttSelectTime);
	    	Button bttCancel = (Button) findViewById(R.id.bttCancel);
	    	
	    	bttActivate.setEnabled(false);
	    	bttDefault.setEnabled(false);
	    	bttSelectTime.setEnabled(false);
	    	
	    	IS_TIMER_ON = true;
	    	SetVolumne(IS_TIMER_ON);
	    	bttCancel.setText("RESET");
		}
	
	
	public void RestoreSettings() {
		Button bttActivate = (Button) findViewById(R.id.bttActivate);
    	Button bttDefault = (Button) findViewById(R.id.bttDefault);
    	Button bttSelectTime = (Button) findViewById(R.id.bttSelectTime);
    	Button bttCancel = (Button) findViewById(R.id.bttCancel);

    	bttActivate.setEnabled(true);
    	bttDefault.setEnabled(true);
    	bttSelectTime.setEnabled(true);
    	
    	EditText defaultMints = (EditText)findViewById(R.id.timepicker_input);
    	defaultMints.setText(R.string.default_time);
    	UpdateTime(defaultMints.getText().toString());
    	
    	IS_TIMER_ON = false;
    	SetVolumne(IS_TIMER_ON);
    	bttCancel.setText("EXIT");
	}
    private void Counter(Boolean start, long milliSeconds)
    {
    	if(counter == null)
    		counter = new MyCount(milliSeconds,1000);
    	if(start)
    		counter.start();
    	else{
    		counter.cancel();
    		counter=null;
    	}
    	
    }
    private void updateDisplay() {
    	EditText defaultMints = (EditText)findViewById(R.id.timepicker_input);
    	defaultMints.setText(R.string.default_time);
    }
    public Boolean ConfirmationMessageBox(String message, String title){
	 	
    	AlertDialog alertDialog = new AlertDialog.Builder(android_timer.this).create();
    	alertDialog = new AlertDialog.Builder(android_timer.this).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {

		    	Intent homeIntent = new Intent( Intent.ACTION_MAIN );
			    homeIntent.addCategory( Intent.CATEGORY_HOME );
			    startActivity(homeIntent);
        } });
        alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
        	  messageBox_Status =  false;
           
        }}); 
        alertDialog.show();
        return messageBox_Status;
    }
    public void SetVolumne(Boolean isTimerOn)
    {
    	VOLUMN_MODE = getSelectedVolumnMode(isTimerOn);
    	AudioManager   mAudio = (AudioManager) getSystemService(Activity.AUDIO_SERVICE);
    	switch(VOLUMN_MODE)
    	{
    	case 0:
    		mAudio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
    		break;
    	case 1:
            mAudio.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
            mAudio.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);

            break;
        default:
            mAudio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        	mAudio.setMode(CURRENT_RINGERMODE);
            break;
    	}
    	
    	
    }
    private int getSelectedVolumnMode(Boolean isTimerOn) {
		RadioButton rdlVibrateMode = (RadioButton) findViewById(R.id.radioVibrate);
		int volumn = 0;
		if(isTimerOn)
			volumn = rdlVibrateMode.isChecked()  ? 1 : 0;
		else
			volumn= -1;
		return  volumn;
	}
    
    public class MyCount extends CountDownTimer{
    	NumberFormat myFormat = NumberFormat.getInstance();

    public MyCount(long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    myFormat.setMinimumIntegerDigits(2);
    }

    @Override
    public void onFinish() {
    	
    	//EditText Input_TimePicker = (EditText)findViewById(R.id.timepicker_input);
		RestoreSettings();
		
    }

    @Override
    public void onTick(long millisUntilFinished) {
    	TextView REMAINING_TIME = (TextView) findViewById(R.id.lblTime);
    	if(REMAINING_TIME != null){
    		long secs = millisUntilFinished/1000;
    		int mint = (int) (secs / 60) % 60;
    		int hrs = (int) (secs / 60) / 60;
    		secs = secs % 60;
    		REMAINING_TIME.setText("Time Left: " + String.valueOf(myFormat.format(hrs)) + ":" + String.valueOf(myFormat.format(mint)) + ":" + String.valueOf(myFormat.format(secs)));
    		
    	}

    }

    }
}
